package com.mall.order.biz.handler;

import com.mall.commons.tool.exception.BizException;
import com.mall.order.biz.context.CreateOrderContext;
import com.mall.order.biz.context.TransHandlerContext;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.dal.entitys.Stock;
import com.mall.order.dal.persistence.OrderMapper;
import com.mall.order.dal.persistence.StockMapper;
import com.mall.order.dto.CartProductDto;
import com.mall.user.IMemberService;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dto.QueryMemberRequest;
import com.mall.user.dto.QueryMemberResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 *
 */
@Slf4j
@Component
public class ValidateHandler extends AbstractTransHandler {

    @Reference(check = false)
    private IMemberService memberService;

    @Autowired
    private StockMapper stockMapper;
    /**
     * 验证用户合法性
     * @return
     */

    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    public boolean handle(TransHandlerContext context) {
        // 验证限购数量
        CreateOrderContext createOrderContext = (CreateOrderContext) context;
        List<CartProductDto> dtoList = createOrderContext.getCartProductDtoList();
        for (CartProductDto cartProductDto : dtoList) {
            Stock stock = stockMapper.selectStock(cartProductDto.getProductId());
            if (stock == null) throw new BizException(OrderRetCode.STOCK_NOT_INITIALIZED.getCode(), OrderRetCode.STOCK_NOT_INITIALIZED.getMessage());
            if (cartProductDto.getProductNum() > stock.getRestrictCount()) throw new BizException("超出限购数量！");
        }
        return true;
    }
}
